package com.crm.backend.controller;


import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.backend.domain.entity.RestBean;
import com.crm.backend.domain.po.SysUser;
import com.crm.backend.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dyy
 * @since 2025-05-30
 */
@RestController
@RequestMapping("/api/v1/sys-user")
public class SysUserController {

    @Autowired
    private ISysUserService sysUserService;

    // 添加用户
    @PostMapping
    public RestBean<SysUser> addUser(@RequestBody SysUser user) {
        // 对密码进行 MD5 加密
        String encryptedPwd = DigestUtil.md5Hex(user.getSuPwd());
        System.out.println(encryptedPwd);
        user.setSuPwd(encryptedPwd);

        boolean saved = sysUserService.save(user);

        if (saved) {
            return RestBean.success(user);
        } else {
            return RestBean.failure(500, "添加用户失败");
        }
    }

    // 根据ID删除用户
    @DeleteMapping
    public RestBean<Void> deleteUser(@RequestParam(value = "id") Integer id) {
        boolean removed = sysUserService.removeById(id);
        if (removed) {
            return RestBean.success();
        } else {
            return RestBean.failure(500, "删除用户失败");
        }
    }

    // 更新用户信息
    @PutMapping
    public RestBean<SysUser> updateUser(@RequestParam(value = "id") Integer id, @RequestBody SysUser user) {
        user.setSuId(id); // 确保更新的是正确的用户
        boolean updated = sysUserService.updateById(user);
        if (updated) {
            return RestBean.success();
        } else {
            return RestBean.failure(500, "更新用户失败");
        }
    }

    // 分页查询用户
    @GetMapping("/page")
    public RestBean<IPage<SysUser>> getUsersByPage(
            @RequestParam(value = "suName", required = false) String suName,
            @RequestParam(value = "page") Integer page,
            @RequestParam(value = "size") Integer size) {
        // 创建分页查询对象
        Page<SysUser> pageQuery = new Page<>(page, size);
        // 创建查询条件
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        // 如果用户名不为空，则添加过滤条件
        if (suName != null) {
            queryWrapper.eq(SysUser::getSuName, suName);
        }
        // 执行分页查询
        IPage<SysUser> userPage = sysUserService.page(pageQuery, queryWrapper);
        // 封装分页结果并返回
        return RestBean.success(userPage);
    }
}
